<template>
  <view class="checkout-page">
    <view class="search-bar">
        <view style="display: flex; align-items: center;">
          <uni-search-bar cancelButton="none" clearButton="none" @confirm="onSearch" placeholder="条码/名称/拼音码" bgColor="#fff" style="flex: 1;"></uni-search-bar>
          <view @click="startScan" style="width: 80px;height: 75px;display: flex; align-items: center; justify-content: center;background-color: #007aff;">
            <image style="width: 50px;height: 50px;" src="/static/icon/扫码.png"></image>
          </view>
        </view>
      </view>
    <!-- 商品列表头部 -->
    <view class="product-header">
      <view class="header-item name-code">商品/条形</view>
      <view class="header-item">数量</view>
      <view class="header-item">单价</view>
      <view class="header-item">小计</view>
    </view>
<!-- 主体内容容器 -->
    <view class="content-container">
      <!-- 商品列表 -->
      <view v-if="products.length > 0" class="product-list">
        <view v-for="(item, index) in products" :key="index" class="product-item">
          <view class="product-info">
            <view class="product-name">{{ item.name }}</view>
            <view class="product-code" style="color:#a4a4a4;">{{ item.code }}</view>
          </view>
          <view class="product-quantity">x{{ item.quantity }}</view>
          <view class="product-price">¥{{ formatAmount(item.price) }}</view>
          <view class="product-total">¥{{ formatAmount(item.total) }}</view>
        </view>
      </view>
	  
      <!-- 清空商品按钮 -->
      <view v-if="products.length > 0" class="summary">
            <view class="total-products">共 {{ totalProducts }} 件商品</view>
            <view @click="clearProducts" class="clear-button">清空商品</view>
      </view>
      <!-- 订单备注 -->
      <view v-if="products.length > 0" class="order-notes">
        <input v-model="orderNotes" placeholder="添加订单备注" />
      </view>
	  <!-- 扫码提示区域 -->
	    <view v-if="products.length === 0" class="pull-down-scan" @click="startScan">
	          <view><image src="/static/icon/下箭头.png" mode="aspectFit"></image></view>
	          <view><text>点击按钮 扫码开单</text></view>
	    </view>
		<!-- 当没有商品时显示的提示 -->
		<view v-if="products.length === 0" class="no-products-tip">
		        暂无商品，请点击按钮扫码添加商品。
		</view>
    </view>
	 
	 <!-- 固定在页面底部的 footer -->
    <view class="footer">
      <button class="delivery-method">选择配送方式</button>
      <button class="settlement" @click="onSettlement">结算：¥{{ formatAmount(totalAmount) }}</button>
    </view>
  </view>
</template>

<script setup>
import { ref,computed  } from 'vue';

const products = ref([
  {
    name: '优酸乳饮料–蓝莓味',
    code: '6900000000000',
    quantity: 1,
    price: 3.00,
    total: 0
  },
  {
    name: '优酸乳饮料–草莓嗯嗯嗯味',
    code: '6900000000000',
    quantity: 1,
    price: 3.00,
    total: 0
  }
]);
// 更新每个商品的小计
products.value.forEach(item => {
  item.total = (item.quantity * item.price);
});

const orderNotes = ref('');
const totalProducts = computed(() => products.value.length);
const totalAmount = computed(() => products.value.reduce((acc, curr) => acc + parseFloat(curr.total), 0));


function onSearch(query) {
	console.log(query)
  // Handle search logic
}

function clearProducts() {
	 wx.showModal({
	    title: '提示',
	    content: '确定清空商品？',
	    success(res) {
	      if (res.confirm) {
	        // 用户点击了确定按钮
	        products.value = [];
	        orderNotes.value = '';
	        // totalProducts.value = 0;
	        // totalAmount.value = 0;	
	      } else if (res.cancel) {
	        // 用户点击了取消按钮，这里可以不写任何逻辑，或者添加一些取消时的操作
	        console.log('用户点击了取消');
	      }
	    },
	    fail(err) {
	      console.error('调用 showModal 方法失败', err);
	    }
	  });
}

function onSettlement() {
  // Handle settlement logic
}

// 金额格式化函数
const formatAmount = (value) => {
  return Number(value).toFixed(2);
};

// 开始扫描的方法
async function startScan() {
  try {
    const res = await new Promise((resolve, reject) => {
      uni.scanCode({
        scanType: ['barCode', 'qrCode'], // 指定扫码类型
        success: resolve,
        fail: reject
      });
    });
    console.log('Scan result:', res.result);
    // 根据扫码结果添加商品到商品列表
    addProductByBarcode(res.result);
  } catch (err) {
    console.error('Detailed scan error:', err.errMsg);
    if (err.errMsg.includes("not supported")) {
      console.warn("The current environment does not support the scanCode method.");
    } else if (err.errMsg.includes("fail")) {
      console.warn("Failed to scan code. Please check if camera permissions are granted and try again.");
    }
  }
}
// 添加商品到列表的函数
function addProductByBarcode(barcode) {
  // 根据barcode查询商品详情（实际应用中可能需要发起网络请求）
  // 为了演示，直接添加一个新商品
  const newProduct = {
    name: '通过条码添加的商品',
    code: barcode,
    quantity: 1,
    price: 9.99,
    total: 9.99
  };
  products.value.push(newProduct);
}
</script>

<style scoped>
.checkout-page {
  width: 100%;
  height: 90vh; /* 确保至少占满整个视口高度 */
  background-color: #f3f4f6;
  display: flex;
  flex-direction: column;
}
.content-container {
  flex: 1;
  overflow-y: auto;
  background-color: #f3f4f6;
  padding-bottom: 30px;
}
.search-bar {
	padding: 0px;
	height: 70px;
	line-height: 70px;
  position: sticky;
  top: 0;
  z-index: 10;
  background-color: #f3f4f6; /* 与背景颜色一致，避免视觉上的突兀 */
}
/* 添加样式以支持商品列表头部 */
.product-header {
  display: flex;
  flex-direction: row;
  justify-content: space-around;
  align-items: center;
  padding: 10px;
  background-color: #e6e6e6;
  font-weight: bold;
  position: sticky;
  top: 70px; /* 与 .search-bar 的高度相匹配 */
  z-index: 10;
}

.header-item {
  text-align: center;
}
.header-item.name-code {
  width: 28%; /* 根据实际需要调整 */
}
.product-item {
  border-radius: 10px;
  font-size: 16px;
  margin: 15px;
  display: flex;
  justify-content: space-between;
  align-items: flex-start; /* 修改为flex-start以适应顶部对齐 */
  padding: 13px;
  border-bottom: 1px solid #ddd;
  background-color:#fff ;
}

.product-info {
  width: 38%; /* 调整宽度以适应两个文本行 */
  display: flex;
  flex-direction: column;
}

/* 确保商品名称在超过指定宽度时显示省略号 */
.product-name {
  width: 100%;
  box-sizing: border-box;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.product-code {
  width: 100%;
  box-sizing: border-box;
  color: #a4a4a4;
  padding-top: 5px;
}
.product-total{
	word-break: break-all; /* 允许长单词或URL地址换行到下一行 */
	white-space: pre-wrap; /* 保留空白符序列，但是正常地进行换行 */
}
.product-quantity, .product-price, .product-total {
  width: 16%; /* 100% / 6 (考虑到有4个主要区域 + 空隙)，适当调整 */
  text-align: center;
  padding-top: 27px;
}

.summary {
  margin:0px 15px 10px 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 16px;
}
.clear-button {
  margin-left: 10px;
  cursor: pointer;
}

.order-notes {
  color: #0059df;
  margin:0px 15px 15px 15px;
}

.footer {
   position: fixed;
    bottom: 0px;
    left: 0;
    right: 0;
    background-color: white;
    padding: 10px;
    box-shadow: 0 -2px 4px rgba(0, 0, 0, 0.1);
    z-index: 1000;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.delivery-method,
.settlement {
  width: 45%;
  height: 50px;
  border-radius: 8px;
  font-size: 18px;
  text-align: center;
  line-height: 50px;
  background-color: #007aff;
  color: #fff;
}

.delivery-method {
  background-color: #ddd;
  color: #333;
}
/* 没有商品的时候，添加 no-products-tip 样式 */
.no-products-tip {
  text-align: center;
  font-size: 16px;
  color: #565656;
  margin-top: 180px;
}

.pull-down-scan {
  font-size: 24px;
  font-weight: bold;
  color: #035be0;
  display: flex;
  flex-direction: column;
  width: 100%;
  text-align: center;
  margin-top: 200px;
}

.pull-down-scan image {
  width: 70px;
  height: 70px;
}
</style>